package cn.com.callback

import cn.com.elite.EliteBean
import cn.com.elite.Util
import cn.com.kh.KHDBConfig
import cn.com.kh.KHUtil
import cn.com.kh.LogToDB
import cn.com.kh.signUtil
import com.alibaba.fastjson.JSONArray
import net.sf.json.JSONObject
import com.alibaba.fastjson.parser.Feature
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import sun.misc.BASE64Decoder
import sun.misc.BASE64Encoder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse
import java.lang.reflect.Array
import java.text.SimpleDateFormat

/**
 * 法大大认证回调接口
 */

public class apiCustomerCallback implements ServiceBackInvoke {
    private static final Log log = LogFactory.getLog(apiCustomerCallback.class);
    private static String APPKEY;
    private static String APPID;

    public String doCallBack(EliteBean eliteBean, HttpServletRequest request, HttpServletResponse response) {

        long startTime = System.currentTimeMillis();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        // 初始化返回参数
        JSONObject result = new JSONObject();

        JSONObject resultJson = null;
        //接收客户端调用参数
        String callJson = "";
        InputStreamReader reader = new InputStreamReader(request.getInputStream(), "UTF-8");
        BufferedReader iny = new BufferedReader(reader);
        String line;
        while ((line = iny.readLine()) != null) {
            callJson += line;
        }

        log.info("[调用请求信息]:" + callJson);
        try {
            APPKEY = KHDBConfig.getParam(eliteBean, "FDDKEY");
            APPID = KHDBConfig.getParam(eliteBean, "FDDID");

            JSONObject inJson = JSONObject.fromObject(callJson);
            String bizContents = inJson.getString("bizContent");
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(bizContents);
            log.debug("bizContent解密：" + new String(bytes))
            String bizContent = URLDecoder.decode(new String(bytes), "UTF-8");
            log.debug("bizContent转码：" + bizContent);
            JSONObject bizContentJson = JSONObject.fromObject(bizContent);

            //获取客户编号
            String customerId = bizContentJson.getString("customerId");
            //获取平台ID
            String appId = bizContentJson.getString("appId");
            //获取serialNo
            String serialNo = bizContentJson.getString("serialNo");
            //获取状态
            String status = bizContentJson.getString("status");
            //获取状态描述
            String statusDesc = bizContentJson.getString("statusDesc");
            String auditFailReason = "";
            if (status == "4" || status == "5") {
                //获取失败原因
                auditFailReason = bizContentJson.getString("auditFailReason");
            }

            List<Object> valueList = new ArrayList<Object>();
            String objupdatesql = "";
            if (!auditFailReason) {
                objupdatesql = "update customer set fdd_status=? where fdd_customerid=?";
                valueList.add(status);
                valueList.add(customerId);
            } else {
                objupdatesql = "update customer set fdd_status=?,fdd_reason=? where fdd_customerid=?";
                valueList.add(status);
                valueList.add(auditFailReason);
                valueList.add(customerId);

            }
            log.debug("参数值：" + valueList.toString());
            int tabcResule = jt.update(objupdatesql, valueList.toArray());

            result.put("code", "0");
        } catch (Exception e) {
            result.put("code", 1008);
            result.put("msg", e.getMessage());
        } finally {
            LogToDB.toDB(eliteBean, "dataSource", "法大大认证回调接口", "apiCustomerCallback", callJson, result.toString(), (System.currentTimeMillis() - startTime).toString(), "/");
        }
        return result.toString();
    }


    //获取合同模板控件
    public String getSign(String bizContent, String datetime) {
        String signString = "appId=" + APPID + "&bizContent=" + bizContent + "&signType=SHA256&timestamp=" + datetime;
        signString = signString.replace("\\n", "");
        log.debug("signString:" + signString);
        String signstr1 = Util.getSHA256Str(signString).toUpperCase();
        log.debug("signstr1:" + signstr1);
        log.debug("signstr1:" + signstr1 + APPKEY);
        String signstr2 = Util.getSHA256Str(signstr1 + APPKEY).toUpperCase();
        log.debug("signstr2:" + signstr2);
        String sign = new BASE64Encoder().encodeBuffer(signstr2.getBytes("UTF-8"));
        return sign;
    }

    //获取bizContent
    public static String getbizContent(String param) {
        log.debug("param:" + param);
        String encodedObject = URLEncoder.encode(param, "UTF-8");
        String biz_contents = new BASE64Encoder().encodeBuffer(encodedObject.getBytes("UTF-8"));
        log.info("[biz_contents]:" + biz_contents);
        return biz_contents;
    }
}